import { Actions, ActTypes } from "./action";

export { epic } from "./epic";

export interface IPost {
  title: string;
  source: string;
  pageview: number;
  hotspot: boolean;
}

export interface StateLoading {
  [key: string]: boolean;
}

export interface DataState {
  headerTitle: string;
  categoryList: string[];
  activeCategory: string;
  posts: {
    [key: string]: IPost[];
  };
}

export interface UIState {
  loading: StateLoading;
}

export type State = DataState & UIState;

const initialState: State = {
  headerTitle: "有趣新闻",
  categoryList: [],
  activeCategory: "",
  posts: {},
  loading: {}
};

export const reducer = (
  state: State = { ...initialState },
  action: Actions
): State => {
  switch (action.type) {
    case ActTypes.Destroy: {
      return { ...initialState };
    }
    case ActTypes.SetCategoryList: {
      const { activeCategory } = state;
      const active =
        (activeCategory ? activeCategory : action.payload[0]) || "";
      return { ...state, categoryList: action.payload, activeCategory: active };
    }
    case ActTypes.SetCategoryActive: {
      return { ...state, activeCategory: action.payload };
    }
    case ActTypes.SetPosts: {
      return { ...state, posts: action.payload };
    }
    default:
      return state;
  }
};
